# -*- coding: utf-8 -*-
"""
设置窗口模块
实现系统设置界面，包括主题设置、语言设置等
"""

import sys
import json
import os
from PySide2.QtWidgets import (
    QDialog, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, 
    QGroupBox, QGridLayout, QSpacerItem, QSizePolicy,
    QCheckBox, QLineEdit, QFileDialog, QMessageBox, QTextEdit
)
from PySide2.QtCore import Qt, Signal
from PySide2.QtGui import QFont, QIcon

from gglobal import logger, config
from ..widget.custom_combo_box import CustomComboBox, ComboBoxStyle, ThemeMode
from ..widget.custom_spinbox import CustomSpinBox, SpinBoxStyle, ThemeMode as SpinBoxThemeMode


class SettingsWindow(QDialog):
    """
    设置窗口类
    提供系统设置功能，包括主题、语言等配置
    """
    
    # 定义信号
    settings_changed = Signal()
    
    def __init__(self, parent=None):
        super(SettingsWindow, self).__init__(parent)
        self.parent_window = parent
        self.language_manager = None
        if parent and hasattr(parent, 'language_manager'):
            self.language_manager = parent.language_manager
        self.setObjectName("settings_window")
        self.init_ui()
        self.load_current_settings()
        self.register_language_widgets()
        
    def init_ui(self):
        """初始化UI"""
        self.setWindowTitle("系统设置")
        self.setFixedSize(600, 1000)
        self.setWindowIcon(QIcon(":/icon/tool.svg"))
        
        # 获取当前主题
        self.current_theme = "light"  # 默认主题
        if self.parent_window and hasattr(self.parent_window, 'theme_manager'):
            self.current_theme = self.parent_window.theme_manager.get_current_theme_name()
        # 创建主布局
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(20, 20, 20, 20)
        main_layout.setSpacing(15)
        
        # 创建设置组
        self.create_appearance_group(main_layout)
        self.create_language_group(main_layout)
        self.create_general_group(main_layout)
        self.create_ssh_group(main_layout)
        
        # 添加弹性空间
        main_layout.addItem(QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding))
        
        # 创建按钮区域
        self.create_button_area(main_layout)
        
        logger.info("设置窗口UI初始化完成")
        
    def create_appearance_group(self, layout):
        """创建外观设置组"""
        self.appearance_group = QGroupBox("外观设置")
        self.appearance_group.setObjectName("appearance_group")
        appearance_layout = QGridLayout(self.appearance_group)
        appearance_layout.setSpacing(10)
        
        # 主题设置
        self.theme_label = QLabel("主题:")
        self.theme_label.setObjectName("settings_label")
        self.theme_combo = CustomComboBox(theme=self.current_theme)
        self._load_available_themes()
        self.theme_combo.currentTextChanged.connect(self.on_theme_changed)
        
        appearance_layout.addWidget(self.theme_label, 0, 0)
        appearance_layout.addWidget(self.theme_combo, 0, 1)
        

        
        layout.addWidget(self.appearance_group)
        
    def create_language_group(self, layout):
        """创建语言设置组"""
        self.language_group = QGroupBox("语言设置")
        self.language_group.setObjectName("language_group")
        language_layout = QGridLayout(self.language_group)
        language_layout.setSpacing(10)
        
        # 语言设置
        self.language_label = QLabel("界面语言:")
        self.language_label.setObjectName("settings_label")
        self.language_combo = CustomComboBox(theme=self.current_theme)
        self.language_combo.addItems(["中文", "English"])
        self.language_combo.currentTextChanged.connect(self.on_language_changed)
        
        language_layout.addWidget(self.language_label, 0, 0)
        language_layout.addWidget(self.language_combo, 0, 1)
        
        layout.addWidget(self.language_group)
        
    def _load_available_themes(self):
        """加载可用的主题"""
        try:
            # 获取主题管理器
            if self.parent_window and hasattr(self.parent_window, 'theme_manager'):
                theme_manager = self.parent_window.theme_manager
                available_themes = theme_manager.get_available_themes()
                
                # 创建主题名称映射
                self.theme_name_map = {}
                theme_display_names = []
                
                for theme_name in available_themes:
                    # 直接使用主题文件名作为显示名称
                    display_name = theme_name
                    
                    self.theme_name_map[display_name] = theme_name
                    theme_display_names.append(display_name)
                
                self.theme_combo.addItems(theme_display_names)
                logger.info(f"加载了 {len(available_themes)} 个可用主题: {available_themes}")
            else:
                # 如果无法访问主题管理器，使用默认主题
                self.theme_combo.addItems(["light", "acrylic"])
                self.theme_name_map = {"light": "light", "acrylic": "acrylic"}
                logger.warning("无法访问主题管理器，使用默认主题列表")
                
        except Exception as e:
            logger.error(f"加载可用主题失败: {e}")
            # 出错时使用默认主题
            self.theme_combo.addItems(["light", "acrylic"])
            self.theme_name_map = {"light": "light", "acrylic": "acrylic"}
        
    def create_general_group(self, layout):
        """创建常规设置组"""
        self.general_group = QGroupBox("常规设置")
        self.general_group.setObjectName("general_group")
        general_layout = QGridLayout(self.general_group)
        general_layout.setSpacing(10)
        
        # 保存日志到文件
        self.save_log_checkbox = QCheckBox("保存日志到文件")
        self.save_log_checkbox.setObjectName("settings_checkbox")
        general_layout.addWidget(self.save_log_checkbox, 0, 0, 1, 2)
        
        # 默认文件路径
        self.path_label = QLabel("默认路径:")
        self.path_label.setObjectName("settings_label")
        self.path_edit = QLineEdit()
        self.path_edit.setObjectName("settings_input")
        self.path_edit.setPlaceholderText("选择默认文件路径")
        self.path_button = QPushButton("浏览...")
        self.path_button.setObjectName("settings_button")
        self.path_button.clicked.connect(self.browse_default_path)
        
        path_layout = QHBoxLayout()
        path_layout.addWidget(self.path_edit)
        path_layout.addWidget(self.path_button)
        
        general_layout.addWidget(self.path_label, 1, 0)
        general_layout.addLayout(path_layout, 1, 1)
        
        # ROS版本设置
        self.ros_label = QLabel("ROS版本:")
        self.ros_label.setObjectName("settings_label")
        self.ros_combo = CustomComboBox(theme=self.current_theme)
        self.ros_combo.addItems(["ROS1", "ROS2"])
        
        general_layout.addWidget(self.ros_label, 2, 0)
        general_layout.addWidget(self.ros_combo, 2, 1)
        
        # 新增：ROS包版本设置
        self.bag_version_label = QLabel("ROS包版本:")
        self.bag_version_label.setObjectName("settings_label")
        self.bag_version_combo = CustomComboBox(theme=self.current_theme)
        self.bag_version_combo.addItems(["new", "old"])
        
        general_layout.addWidget(self.bag_version_label, 3, 0)
        general_layout.addWidget(self.bag_version_combo, 3, 1)
        
        # 新增：车辆类型设置
        self.vehicle_label = QLabel("车辆类型:")
        self.vehicle_label.setObjectName("settings_label")
        self.vehicle_combo = CustomComboBox(theme=self.current_theme)
        self._load_available_vehicles()
        
        general_layout.addWidget(self.vehicle_label, 4, 0)
        general_layout.addWidget(self.vehicle_combo, 4, 1)
        
        # 转换话题列表设置
        self.topic_label = QLabel("转换话题列表:")
        self.topic_label.setObjectName("settings_label")
        self.topic_text = QTextEdit()
        self.topic_text.setObjectName("settings_text")
        self.topic_text.setMaximumHeight(100)
        
        general_layout.addWidget(self.topic_label, 5, 0)
        general_layout.addWidget(self.topic_text, 5, 1)
        
        # 地图文件路径设置
        self.map_path_label = QLabel("地图文件路径:")
        self.map_path_label.setObjectName("settings_label")
        self.map_path_edit = QLineEdit()
        self.map_path_edit.setObjectName("settings_edit")
        self.map_path_button = QPushButton("浏览")
        self.map_path_button.setObjectName("settings_button")
        self.map_path_button.clicked.connect(self.browse_map_path)
        
        map_layout = QHBoxLayout()
        map_layout.addWidget(self.map_path_edit)
        map_layout.addWidget(self.map_path_button)
        
        general_layout.addWidget(self.map_path_label, 6, 0)
        general_layout.addLayout(map_layout, 6, 1)
        
        layout.addWidget(self.general_group)
        
    def create_ssh_group(self, layout):
        """创建SSH设置组"""
        self.ssh_group = QGroupBox("SSH设置")
        self.ssh_group.setObjectName("ssh_group")
        ssh_layout = QGridLayout(self.ssh_group)
        ssh_layout.setSpacing(10)
        
        # SSH端口设置
        self.ssh_port_label = QLabel("SSH端口:")
        self.ssh_port_label.setObjectName("settings_label")
        self.ssh_port_spinbox = CustomSpinBox(theme=self.current_theme, style=SpinBoxStyle.DEFAULT)
        self.ssh_port_spinbox.setRange(1, 65535)
        self.ssh_port_spinbox.setValue(22)
        
        ssh_layout.addWidget(self.ssh_port_label, 0, 0)
        ssh_layout.addWidget(self.ssh_port_spinbox, 0, 1)
        
        # SSH用户名设置
        self.ssh_username_label = QLabel("SSH用户名:")
        self.ssh_username_label.setObjectName("settings_label")
        self.ssh_username_edit = QLineEdit()
        self.ssh_username_edit.setObjectName("settings_input")
        self.ssh_username_edit.setPlaceholderText("输入SSH用户名")
        
        ssh_layout.addWidget(self.ssh_username_label, 1, 0)
        ssh_layout.addWidget(self.ssh_username_edit, 1, 1)
        
        # SSH密码设置
        self.ssh_password_label = QLabel("SSH密码:")
        self.ssh_password_label.setObjectName("settings_label")
        self.ssh_password_edit = QLineEdit()
        self.ssh_password_edit.setObjectName("settings_input")
        self.ssh_password_edit.setPlaceholderText("输入SSH密码")
        self.ssh_password_edit.setEchoMode(QLineEdit.Password)
        
        ssh_layout.addWidget(self.ssh_password_label, 2, 0)
        ssh_layout.addWidget(self.ssh_password_edit, 2, 1)
        
        # SSH远程文件夹路径设置
        self.ssh_remote_folder_label = QLabel("远程文件夹路径:")
        self.ssh_remote_folder_label.setObjectName("settings_label")
        self.ssh_remote_folder_edit = QLineEdit()
        self.ssh_remote_folder_edit.setObjectName("settings_input")
        self.ssh_remote_folder_edit.setPlaceholderText("输入远程文件夹路径")
        
        ssh_layout.addWidget(self.ssh_remote_folder_label, 3, 0)
        ssh_layout.addWidget(self.ssh_remote_folder_edit, 3, 1)
        
        layout.addWidget(self.ssh_group)
        
    def create_button_area(self, layout):
        """创建按钮区域"""
        button_layout = QHBoxLayout()
        button_layout.addStretch()
        
        # 应用按钮
        self.apply_button = QPushButton("应用")
        self.apply_button.setObjectName("settings_button")
        self.apply_button.clicked.connect(self.apply_settings)
        
        # 取消按钮
        self.cancel_button = QPushButton("取消")
        self.cancel_button.setObjectName("settings_button")
        self.cancel_button.clicked.connect(self.reject)
        
        button_layout.addWidget(self.apply_button)
        button_layout.addWidget(self.cancel_button)
        
        layout.addLayout(button_layout)
        
    def register_language_widgets(self):
        """注册语言控件"""
        if not self.language_manager:
            return
            
        try:
            # 注册窗口标题
            self.language_manager.register_widget(self, "settings_window_title", "windowTitle")
            
            # 注册组框标题
            if hasattr(self, 'appearance_group'):
                self.language_manager.register_widget(self.appearance_group, "appearance_group_title", "title")
            if hasattr(self, 'language_group'):
                self.language_manager.register_widget(self.language_group, "language_group_title", "title")
            if hasattr(self, 'general_group'):
                self.language_manager.register_widget(self.general_group, "general_group_title", "title")
            if hasattr(self, 'ssh_group'):
                self.language_manager.register_widget(self.ssh_group, "ssh_group_title", "title")
            
            # 注册标签
            if hasattr(self, 'theme_label'):
                self.language_manager.register_widget(self.theme_label, "theme_label")

            if hasattr(self, 'language_label'):
                self.language_manager.register_widget(self.language_label, "language_label")
            if hasattr(self, 'path_label'):
                self.language_manager.register_widget(self.path_label, "default_path_label")
            if hasattr(self, 'ros_label'):
                self.language_manager.register_widget(self.ros_label, "ros_version_label")
            if hasattr(self, 'bag_version_label'):
                self.language_manager.register_widget(self.bag_version_label, "bag_version_label")
            if hasattr(self, 'vehicle_label'):
                self.language_manager.register_widget(self.vehicle_label, "vehicle_label")
            if hasattr(self, 'topic_label'):
                self.language_manager.register_widget(self.topic_label, "topic_label")
            if hasattr(self, 'map_path_label'):
                self.language_manager.register_widget(self.map_path_label, "map_path_label")
            if hasattr(self, 'ssh_port_label'):
                self.language_manager.register_widget(self.ssh_port_label, "ssh_port_label")
            if hasattr(self, 'ssh_username_label'):
                self.language_manager.register_widget(self.ssh_username_label, "ssh_username_label")
            if hasattr(self, 'ssh_password_label'):
                self.language_manager.register_widget(self.ssh_password_label, "ssh_password_label")
            if hasattr(self, 'ssh_remote_folder_label'):
                self.language_manager.register_widget(self.ssh_remote_folder_label, "ssh_remote_folder_label")
            
            # 注册复选框
            if hasattr(self, 'save_log_checkbox'):
                self.language_manager.register_widget(self.save_log_checkbox, "save_log_checkbox")
            
            # 注册按钮
            if hasattr(self, 'apply_button'):
                self.language_manager.register_widget(self.apply_button, "apply_button")
            if hasattr(self, 'cancel_button'):
                self.language_manager.register_widget(self.cancel_button, "cancel_button")
            if hasattr(self, 'path_button'):
                self.language_manager.register_widget(self.path_button, "browse_button")
            if hasattr(self, 'map_path_button'):
                self.language_manager.register_widget(self.map_path_button, "map_path_button")
            
            # 注册输入框占位符
            if hasattr(self, 'path_edit'):
                self.language_manager.register_widget(self.path_edit, "path_placeholder", "placeholderText")
            if hasattr(self, 'ssh_username_edit'):
                self.language_manager.register_widget(self.ssh_username_edit, "ssh_username_placeholder", "placeholderText")
            if hasattr(self, 'ssh_password_edit'):
                self.language_manager.register_widget(self.ssh_password_edit, "ssh_password_placeholder", "placeholderText")
            if hasattr(self, 'ssh_remote_folder_edit'):
                self.language_manager.register_widget(self.ssh_remote_folder_edit, "ssh_remote_folder_placeholder", "placeholderText")
            
            logger.info("设置窗口语言控件注册完成")
        except Exception as e:
            logger.error(f"注册语言控件失败: {e}")
        
    def load_current_settings(self):
        """加载当前设置"""
        try:
            # 加载主题设置
            current_theme = config.get_param("current_theme") or "light"
            
            # 根据主题名称映射找到对应的显示名称
            theme_name_map = getattr(self, 'theme_name_map', {"light": "light", "acrylic": "acrylic"})
            display_name = None
            for display, theme in theme_name_map.items():
                if theme == current_theme:
                    display_name = display
                    break
            
            if display_name:
                self.theme_combo.setCurrentText(display_name)
            else:
                # 如果找不到对应的显示名称，默认选择第一个
                if self.theme_combo.count() > 0:
                    self.theme_combo.setCurrentIndex(0)
                
            # 加载语言设置
            current_language = config.get_param("current_language") or "zh_CN"
            if current_language == "zh_CN":
                self.language_combo.setCurrentText("中文")
            else:
                self.language_combo.setCurrentText("English")
                
            # 加载其他设置
            save_log = config.get_param("save_log_to_file") or False
            self.save_log_checkbox.setChecked(save_log)
            
            default_path = config.get_param("last_opened_file") or ""
            self.path_edit.setText(default_path)
            
            ros_version = config.get_param("version") or "ROS1"
            self.ros_combo.setCurrentText(ros_version)
            
            # 加载新增设置项
            self.load_additional_settings()
            
            # 加载SSH设置项
            self.load_ssh_settings()
            
            logger.info("当前设置加载完成")
            
        except Exception as e:
            logger.error(f"加载设置失败: {e}")
            
    def on_theme_changed(self, theme_text):
        """主题改变事件"""
        theme_name = getattr(self, 'theme_name_map', {"light": "light", "acrylic": "acrylic"}).get(theme_text, "light")
        self.apply_theme(theme_name)
        
    def on_language_changed(self, language_text):
        """语言改变事件"""
        language_code = "zh_CN" if language_text == "中文" else "en_US"
        self.apply_language(language_code)
        
    def apply_theme(self, theme_name):
        """应用主题"""
        try:
            if self.parent_window and hasattr(self.parent_window, 'theme_manager'):
                self.parent_window.theme_manager.apply_theme(theme_name)
                # 更新当前主题
                self.current_theme = theme_name
                # 更新所有CustomComboBox的主题
                self._update_combo_themes(theme_name)
                logger.info(f"主题应用成功: {theme_name}")
        except Exception as e:
            logger.error(f"主题应用失败: {e}")
            
    def _update_combo_themes(self, theme_name):
        """更新所有CustomComboBox和CustomSpinBox的主题"""
        try:
            # 更新所有CustomComboBox的主题
            combo_boxes = [self.theme_combo, self.language_combo, self.ros_combo, 
                          self.bag_version_combo, self.vehicle_combo]
            for combo in combo_boxes:
                if hasattr(combo, 'update_theme'):
                    combo.update_theme(theme_name)
            
            # 更新所有CustomSpinBox的主题
            spinbox_widgets = [self.ssh_port_spinbox]
            for spinbox in spinbox_widgets:
                if hasattr(spinbox, 'update_theme'):
                    spinbox.update_theme(theme_name)
        except Exception as e:
            logger.error(f"更新控件主题失败: {e}")
            
    def apply_language(self, language_code):
        """应用语言"""
        try:
            if self.parent_window and hasattr(self.parent_window, 'language_manager'):
                self.parent_window.language_manager.set_language(language_code)
                config.set_param("current_language", language_code)
                # 更新设置窗口本身的界面文本
                self.update_ui_language()
                logger.info(f"语言应用成功: {language_code}")
        except Exception as e:
            logger.error(f"语言应用失败: {e}")
            
    def update_ui_language(self):
        """更新设置窗口的界面语言"""
        if not self.language_manager:
            return
            
        try:
            # 更新窗口标题
            title = self.language_manager.get_text("settings_window_title", "系统设置")
            self.setWindowTitle(title)
            logger.info("设置窗口界面语言更新完成")
        except Exception as e:
            logger.error(f"更新设置窗口界面语言失败: {e}")
            
    def browse_default_path(self):
        """浏览默认路径"""
        folder = QFileDialog.getExistingDirectory(
            self, "选择默认路径", self.path_edit.text()
        )
        if folder:
            self.path_edit.setText(folder)
    
    def _load_available_vehicles(self):
        """加载可用的车辆类型列表"""
        vehicle_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "apis", "ros1", "vehicle")
        
        if os.path.exists(vehicle_dir):
            # 获取目录下所有.stl文件，去掉扩展名
            vehicle_files = []
            for file in os.listdir(vehicle_dir):
                if file.endswith('.stl'):
                    vehicle_files.append(os.path.splitext(file)[0])
            
            if vehicle_files:
                self.vehicle_combo.addItems(vehicle_files)
            else:
                self.vehicle_combo.addItem("无可用车辆")
        else:
            self.vehicle_combo.addItem("车辆目录不存在")
    
    def browse_map_path(self):
        """浏览地图文件路径"""
        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择地图文件", "", "地图文件 (*.mooe *.json);;所有文件 (*)"
        )
        if file_path:
            self.map_path_edit.setText(file_path)
            
    def apply_settings(self):
        """应用设置"""
        try:
            # 保存主题设置
            theme_text = self.theme_combo.currentText()
            theme_name_map = getattr(self, 'theme_name_map', {"light": "light", "acrylic": "acrylic"})
            theme_name = theme_name_map.get(theme_text, "light")
            config.set_param("current_theme", theme_name)
            
            # 保存语言设置
            language_text = self.language_combo.currentText()
            language_code = "zh_CN" if language_text == "中文" else "en_US"
            config.set_param("current_language", language_code)
            
            # 保存其他设置
            config.set_param("save_log_to_file", self.save_log_checkbox.isChecked())
            config.set_param("last_opened_file", self.path_edit.text())
             
            # 保存ROS版本
            config.set_param("version", self.ros_combo.currentText())
            
            # 保存新增设置项
            config.set_param("bagversion", self.bag_version_combo.currentText())
            
            # 保存车辆类型
            config.set_param("vehicle", self.vehicle_combo.currentText())
            
            # 保存转换话题列表
            topics_text = self.topic_text.toPlainText().strip()
            if topics_text:
                topics_list = [topic.strip() for topic in topics_text.split('\n') if topic.strip()]
                config.set_param("change_topic", topics_list)
            else:
                config.set_param("change_topic", [])
            
            # 保存地图文件路径
            map_path = self.map_path_edit.text().strip()
            config.set_param("localmap", map_path)
            
            # 保存SSH设置
            config.set_param("port", self.ssh_port_spinbox.value())
            config.set_param("username", self.ssh_username_edit.text().strip())
            config.set_param("password", self.ssh_password_edit.text())
            config.set_param("ssh_remote_folder", self.ssh_remote_folder_edit.text().strip())
            
            # 保存所有配置到文件
            config.save_config()
            
            # 发出设置改变信号
            self.settings_changed.emit()
            
            # 显示成功消息
            QMessageBox.information(self, "设置", "设置已保存")
            
            logger.info("设置应用成功")
            
        except Exception as e:
            logger.error(f"应用设置失败: {e}")
            QMessageBox.critical(self, "错误", f"保存设置失败: {e}")
            

        
    def load_additional_settings(self):
         """加载新增设置项"""
         try:
            # 加载ROS包版本设置
            bag_version = config.get_param('bagversion', 'new')
            self.bag_version_combo.setCurrentText(bag_version)
             
             # 加载车辆类型设置
            vehicle = config.get_param('vehicle', '')
            if vehicle:
                  # 检查配置的车辆类型是否在可用列表中
                  index = self.vehicle_combo.findText(vehicle)
                  if index >= 0:
                      self.vehicle_combo.setCurrentIndex(index)
                  else:
                      # 如果配置的车辆类型不在列表中，默认选择第一个
                      if self.vehicle_combo.count() > 0:
                          self.vehicle_combo.setCurrentIndex(0)
            else:
                  # 如果没有配置车辆类型，默认选择第一个
                  if self.vehicle_combo.count() > 0:
                      self.vehicle_combo.setCurrentIndex(0)
             
             # 加载转换话题列表
            change_topic = config.get_param('change_topic', [])
            if isinstance(change_topic, list):
                 topics_text = '\n'.join(change_topic)
                 self.topic_text.setPlainText(topics_text)
            else:
                 self.topic_text.setPlainText('')
             
             # 加载地图文件路径
            localmap = config.get_param('localmap', '')
            self.map_path_edit.setText(localmap)
             
            logger.info("新增设置项加载完成")
             
         except Exception as e:
             logger.error(f"加载新增设置项失败: {e}")
             
    def load_ssh_settings(self):
        """加载SSH设置项"""
        try:
            # 加载SSH端口设置
            ssh_port = config.get_param('port', 22)
            self.ssh_port_spinbox.setValue(ssh_port)
            
            # 加载SSH用户名设置
            ssh_username = config.get_param('username', '')
            self.ssh_username_edit.setText(ssh_username)
            
            # 加载SSH密码设置
            ssh_password = config.get_param('password', '')
            self.ssh_password_edit.setText(ssh_password)
            
            # 加载SSH远程文件夹路径设置
            ssh_remote_folder = config.get_param('ssh_remote_folder', '')
            self.ssh_remote_folder_edit.setText(ssh_remote_folder)
            
            logger.info("SSH设置项加载完成")
            
        except Exception as e:
            logger.error(f"加载SSH设置项失败: {e}")


if __name__ == "__main__":
    from PySide2.QtWidgets import QApplication
    
    app = QApplication(sys.argv)
    window = SettingsWindow()
    window.show()
    sys.exit(app.exec_())